<template>
  <div class="search-page">
    <a-row :gutter="16">
      <a-col :span="24">
        <a-card title="房源搜索" :bordered="false">
          <a-form layout="inline" :model="searchForm">
            <a-form-item label="城市">
              <a-select
                v-model:value="searchForm.city"
                style="width: 120px"
                placeholder="选择城市"
                @change="handleCityChange"
              >
                <a-select-option v-for="city in cities" :key="city" :value="city">
                  {{ city }}
                </a-select-option>
              </a-select>
            </a-form-item>
            
            <a-form-item label="价格范围">
              <a-slider
                v-model:value="searchForm.priceRange"
                :min="0"
                :max="1000"
                :step="10"
                :range="true"
                style="width: 200px"
                :tipFormatter="(value) => `${value}万`"
              />
              <span class="price-range-text">{{ searchForm.priceRange[0] }}万-{{ searchForm.priceRange[1] }}万</span>
            </a-form-item>
            
            <a-form-item label="面积范围">
              <a-slider
                v-model:value="searchForm.areaRange"
                :min="0"
                :max="200"
                :step="10"
                :range="true"
                style="width: 200px"
                :tipFormatter="(value) => `${value}㎡`"
              />
              <span class="area-range-text">{{ searchForm.areaRange[0] }}㎡-{{ searchForm.areaRange[1] }}㎡</span>
            </a-form-item>
            
            <a-form-item label="户型">
              <a-select
                v-model:value="searchForm.layout"
                style="width: 120px"
                placeholder="选择户型"
                allowClear
              >
                <a-select-option v-for="layout in layoutOptions" :key="layout" :value="layout">
                  {{ layout }}
                </a-select-option>
              </a-select>
            </a-form-item>
            
            <a-form-item label="装修">
              <a-select
                v-model:value="searchForm.decoration"
                style="width: 120px"
                placeholder="选择装修"
                allowClear
              >
                <a-select-option v-for="decoration in decorationOptions" :key="decoration" :value="decoration">
                  {{ decoration }}
                </a-select-option>
              </a-select>
            </a-form-item>
            
            <a-form-item>
              <a-input-search
                v-model:value="searchForm.query"
                placeholder="输入关键词搜索"
                style="width: 200px"
                @search="handleSearch"
              />
            </a-form-item>
            
            <a-form-item>
              <a-button type="primary" @click="handleSearch">搜索</a-button>
              <a-button style="margin-left: 8px" @click="resetForm">重置</a-button>
            </a-form-item>
          </a-form>
        </a-card>
      </a-col>
    </a-row>
    
    <a-row :gutter="16" style="margin-top: 16px">
      <a-col :span="24">
        <a-card :bordered="false">
          <template #title>
            <div class="search-result-header">
              <span>共找到 <a-tag color="blue">{{ totalHouses }}</a-tag> 条结果</span>
              <div class="sort-options">
                <a-radio-group v-model:value="sortOption" @change="handleSortChange">
                  <a-radio-button value="default">默认排序</a-radio-button>
                  <a-radio-button value="priceAsc">价格↑</a-radio-button>
                  <a-radio-button value="priceDesc">价格↓</a-radio-button>
                  <a-radio-button value="areaAsc">面积↑</a-radio-button>
                  <a-radio-button value="areaDesc">面积↓</a-radio-button>
                </a-radio-group>
              </div>
            </div>
          </template>
          
          <a-table
            :dataSource="houses"
            :columns="columns"
            :loading="loading"
            :pagination="{
              current: currentPage,
              pageSize: pageSize,
              total: totalHouses,
              onChange: handlePageChange,
              showSizeChanger: true,
              pageSizeOptions: ['10', '20', '50'],
              onShowSizeChange: handleSizeChange
            }"
            rowKey="id"
          >
            <template #bodyCell="{ column, record }">
              <template v-if="column.dataIndex === 'price'">
                <span class="price">{{ record.price?.totalPriceText }}</span>
                <span class="unit-price">{{ record.price?.unitPriceText }}</span>
              </template>
              
              <template v-if="column.dataIndex === 'area'">
                {{ record.details?.area }}
              </template>
              
              <template v-if="column.dataIndex === 'layout'">
                {{ record.details?.configuration }}
              </template>
              
              <template v-if="column.dataIndex === 'decoration'">
                {{ record.details?.decorate }}
              </template>
              
              <template v-if="column.dataIndex === 'action'">
                <a-space>
                  <router-link :to="`/detail/${record.id}`">
                    <a-button type="link">详情</a-button>
                  </router-link>
                  <a-button type="link" @click="handleCompare(record)">对比</a-button>
                </a-space>
              </template>
            </template>
          </a-table>
        </a-card>
      </a-col>
    </a-row>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted, watch } from 'vue'
import { useHouseStore } from '../stores/houseStore'
import { message } from 'ant-design-vue'

// 初始化 store
const houseStore = useHouseStore()

// 表格列定义
const columns = [
  {
    title: '标题',
    dataIndex: 'title',
    key: 'title',
    ellipsis: true,
    width: 300
  },
  {
    title: '位置',
    dataIndex: 'location',
    key: 'location',
    width: 150
  },
  {
    title: '价格',
    dataIndex: 'price',
    key: 'price',
    width: 150,
    sorter: (a, b) => (a.price?.totalPrice || 0) - (b.price?.totalPrice || 0)
  },
  {
    title: '面积',
    dataIndex: 'area',
    key: 'area',
    width: 100,
    sorter: (a, b) => (a.details?.areaValue || 0) - (b.details?.areaValue || 0)
  },
  {
    title: '户型',
    dataIndex: 'layout',
    key: 'layout',
    width: 100
  },
  {
    title: '朝向',
    dataIndex: 'towards', 
    key: 'towards',
    width: 100,
    render: (text, record) => record.details?.towards
  },
  {
    title: '装修',
    dataIndex: 'decoration',
    key: 'decoration',
    width: 100
  },
  {
    title: '操作',
    dataIndex: 'action',
    key: 'action',
    fixed: 'right',
    width: 120
  }
]

// 搜索表单
const searchForm = reactive({
  city: '',
  priceRange: [0, 1000],
  areaRange: [0, 200],
  layout: undefined,
  decoration: undefined,
  query: ''
})

// 排序选项
const sortOption = ref('default')

// 从 store 获取状态
const houses = computed(() => houseStore.houses)
const totalHouses = computed(() => houseStore.totalHouses)
const loading = computed(() => houseStore.loading)
const currentPage = computed(() => houseStore.currentPage)
const pageSize = computed(() => houseStore.pageSize)
const cities = computed(() => houseStore.cities)

// 选项数据
const layoutOptions = ref(['1室1厅', '2室1厅', '2室1厅', '3室1厅', '3室2厅', '4室2厅', '4室1厅', '复式', '其他'])
const decorationOptions = ref(['精装', '简装', '毛坯', '其他'])

// 监听户型变化
watch(() => searchForm.layout, (newLayout) => {
  console.log('户型选择变化:', newLayout);
  if (newLayout) {
    // 立即更新store中的户型筛选条件
    houseStore.setFilters({
      ...houseStore.filters,
      layout: newLayout
    });
  }
});

// 监听装修变化
watch(() => searchForm.decoration, (newDecoration) => {
  console.log('装修选择变化:', newDecoration);
  if (newDecoration) {
    // 立即更新store中的装修筛选条件
    houseStore.setFilters({
      ...houseStore.filters,
      decoration: newDecoration
    });
  }
});

// 处理城市变化
const handleCityChange = (value) => {
  houseStore.setCity(value)
}

// 处理排序变化
const handleSortChange = (e) => {
  const value = e.target.value;
  houseStore.setSort(value);
  houseStore.fetchHouses();
}

// 处理每页显示条数变化
const handleSizeChange = (current, size) => {
  houseStore.setPageSize(size);
  houseStore.fetchHouses();
}

// 处理搜索
const handleSearch = () => {
  // 更新 store 中的筛选条件
  houseStore.setSearchQuery(searchForm.query)
  houseStore.setFilters({
    priceRange: searchForm.priceRange,
    areaRange: searchForm.areaRange,
    layout: searchForm.layout,
    decoration: searchForm.decoration
  })
  
  // 重置页码
  houseStore.setPage(1);
  
  // 应用筛选条件并搜索
  houseStore.applyFilters()
}

// 重置表单
const resetForm = () => {
  searchForm.priceRange = [0, 1000]
  searchForm.areaRange = [0, 200]
  searchForm.layout = undefined
  searchForm.decoration = undefined
  searchForm.query = ''
  sortOption.value = 'default'
  
  // 重置 store 中的筛选条件
  houseStore.setSearchQuery('')
  houseStore.setSort('default')
  houseStore.setFilters({
    priceRange: [0, 1000],
    areaRange: [0, 200],
    layout: '',
    decoration: ''
  })
  
  // 重置页码
  houseStore.setPage(1);
  
  // 应用筛选条件并搜索
  houseStore.applyFilters()
}

// 处理分页变化
const handlePageChange = (page) => {
  houseStore.setPage(page)
  houseStore.fetchHouses()
}

// 处理添加到对比
const handleCompare = (house) => {
  message.success(`添加房源 ${house.title} 到对比列表`)
  // 这里可以实现添加到对比的逻辑
}

// 页面加载时获取数据
onMounted(async () => {
  try {
    // 获取城市列表
    await houseStore.fetchCities()
    
    // 如果有城市，默认选择第一个
    if (cities.value.length > 0) {
      searchForm.city = cities.value[0]
      await handleCityChange(searchForm.city)
    }
    
    // 获取房源列表
    await houseStore.fetchHouses()
  } catch (error) {
    message.error('获取初始数据失败')
  }
})
</script>

<style scoped lang="scss">
.search-page {
  padding: 24px;
  
  .search-result-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }
  
  .sort-options {
    margin-left: auto;
  }
  
  .price {
    display: block;
    color: #f5222d;
    font-weight: bold;
  }
  
  .unit-price {
    display: block;
    font-size: 12px;
    color: #999;
  }
  
  .price-range-text, .area-range-text {
    margin-left: 10px;
    font-size: 12px;
    color: #666;
  }
}
</style> 